# @File   :  run.py
# @Time   :  2020/05/15 16:19:14
# @Author : hyh
# here put the import lib
import os
import xlrd
from openpyxl import load_workbook
from models import Fake
# 修改此引入, 切换不同的配置文件
from options import example as option


# 初始化文件
def init_file(file_path):
    if os.path.exists(file_path):
        os.remove(file_path)


# 移除格式
def remove_format(text):
    if isinstance(text, str):
        text = text.replace('\n', '').replace(' ', '')
    return text


# 生成列数据
def generate_data(data_list, data_object):
    if isinstance(data_object, dict):
        return Fake(data_option).value()
    elif isinstance(data_option, int):
        temp = data_list[data_option]
        return remove_format(temp) if option.REMOVE_FORMAT else temp
    else:
        return data_object


# 生成SQL
def generate_sql(template, data):
    # 根据参数类型不同, 使用不同的格式化方法
    if isinstance(data, list):
        return template.format(*data)
    elif isinstance(data, dict) or isinstance(data, object):
        return template.format(**data)
    else:
        return template.format(data)


if __name__ == "__main__":
    # 重新初始化文件
    init_file(option.SQL_FILE)
    sql_file = open(option.SQL_FILE, encoding='utf-8', mode="a")
    sql = ''
    read = xlrd.open_workbook(option.EXCEL_FILE).sheet_by_index(0)
    # 生成写文件流
    write_file = load_workbook(option.EXCEL_FILE)
    write = write_file.active
    for row_num in range(1, read.nrows):
        row_data = read.row_values(row_num)
        fake_data = []
        # 根据配置循环生成数据
        for data_option in option.DATA_COL:
            col_data = generate_data(row_data, data_option)
            fake_data.append(col_data)
            if option.REWRITE and isinstance(data_option, int):
                write.cell(row_num + 1, data_option + 1, col_data)
        sql += generate_sql(option.SQL, fake_data) + '\n'
    write_file.save(option.EXCEL_FILE)
    sql = sql[:-1]
    sql_file.write(sql)
